package org.balabala.gateway.redis;

import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.balabala.gateway.entity.Video;
import org.balabala.gateway.feign.VideoFeign;
import org.balabala.gateway.response.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SyncDataService {

    @Autowired
    private VideoManager videoManager;

    @Autowired
    private VideoFeign videoFeign;

    @Async
    @Scheduled(cron = "0/60 * * * * MON-SAT")
    public void syncPlayNum() {
        Map<Long, Video> allVideos = videoManager.getAllVideos();
        Map<Long, Integer> map = new HashMap<>();
        for (Map.Entry<Long, Video> videoEntry : allVideos.entrySet()) {
            map.put(videoEntry.getKey(), videoEntry.getValue().getPlayNum());
        }
        if (map.size() != 0) {
            try {
                Resp resp = videoFeign.setVideoPlayNums(map);
                if (resp.getCode() == 0) {
                    log.info("syncPlayNum update succeed,num : " + map.size());
                } else {
                    log.error("syncPlayNum update failed");
                }
            } catch (FeignException e) {
                log.error("videoFeign.setVideoPlayNums request error : " + e);
            }
        }
    }
}
